#pragma once
#include <iostream>
#include <functional>
#include "Socket.hpp"
#include "InetAddr.hpp"
#include "Protocol.hpp"
#include "Factory.hpp"
using namespace socket_ns;
using namespace protocol_ns;

using dispose_t = std::function<Response(Request)>;

class IOService
{
public:
    IOService(dispose_t dispose)
        :_dispose(dispose)
    {}
    void Service(sock_sptr sptr, InetAddr addr)
    {
        std::string inbuffer;
        while(true)
        {
            //1.获取输入
            sptr->Recv(inbuffer);
            //2.判断是否是一个完整的报文
            std::string message;
            while((message = DeCode(inbuffer)) != "")
            {
                LOG(INFO, "序列化message : %s\n", message.c_str());
                //3.反序列化
                Request q = Factory::CreateRequest();
                q.DeSerialize(message);
                //4.求出结果
                Response rs = _dispose(q);

                //5. 结果序列化
                std::string out;
                rs.Serialize(out);

                //6. 添加抱头
                out = EnCode(out);

                //7. 发送
                sptr->Send(out);
            }
        }
        
    }
    ~IOService()
    {}
private:
    dispose_t _dispose;
};